﻿using iStudio.Structure.Wave;
using WaveFormat = NAudio.Wave.WaveFormat;

namespace iStudio.Engine
{
    /// <summary>
    /// NAudio channel wrapper, represents single channel samples from track
    /// </summary>
    public sealed class NAudioChannel : INAudioStream
    {
        private readonly WaveTrack _track;
        private readonly WaveChannel _channel;

        public NAudioChannel (WaveChannel channel, WaveTrack track)
        {
            _channel = channel;
            _track = track;
        }

        public long Position
        {
            get;
            set;
        }

        public long Length
        {
            get
            {
                return _track.Length;
            }
        }

        public WaveFormat WaveFormat
        {
            get
            {
                return WaveFormat.CreateIeeeFloatWaveFormat(44100, 1);
            }
        }

        public int Read(float[] buffer, int offset, int count)
        {
            int readSamples = 0;
            int outIndex = 0;

            while (readSamples < count)
            {
                buffer[outIndex] = _track.GetSample( ((outIndex + offset + Position) * _track.WaveFormat.Channels) + (int)_channel);

                readSamples++;
                outIndex++;
            }

            Position += count;

            return readSamples;
        }
    }
}
